package com.ruoyi.project.system.picture.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.csource.common.MyException;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.QueryResultsRow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.drools.core.KieTemplate;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.DL4JUtils;
import com.ruoyi.common.utils.FastDFSUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.label.domain.Label;
import com.ruoyi.project.system.picture.domain.Picture;
import com.ruoyi.project.system.picture.service.IPictureService;

/**
 * 图片信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/picture")
public class PictureController extends BaseController {
	private String prefix = "system/picture";
	@Autowired
	private IPictureService pictureService;
	@Autowired
	private KieTemplate kieTemplate;

	/**
	 * 跳转图片管理页面
	 */
	@RequiresPermissions("system:picture:view")
	@GetMapping()
	public String picture(Model m, String num) {
		System.out.println(num);
		if (num == null)
			num = "1";
		PageHelper.startPage(Integer.valueOf(num), 10);
		List<Picture> pictureList = pictureService.selectPictureAll();
		m.addAttribute("pictures", new PageInfo(pictureList));
		return prefix + "/picture";
	}

	@ResponseBody
	@PostMapping("/delete")
	public AjaxResult deletePictures(String ids) throws IOException, MyException {
		for (String val : ids.split(",")) {//遍历需要删除的图片id
			Picture picture = pictureService.selectPicture(Long.valueOf(val));//根据图片ID查询出指定图片
			FastDFSUtils.deleteFile(picture.getSrcPath());//使用FastDFS接口删除原图
			FastDFSUtils.deleteFile(picture.getThumbnailPath());//使用FastDFS接口删除缩略图
		}
		return toAjax(pictureService.deletePictureById(ids));//删除数据库记录并根据结果返回
	}

	/**
	 * 查看原图
	 */
	@GetMapping("/detail/{Id}")
	public String detail(@PathVariable("Id") Long id, ModelMap mmap) {
		mmap.addAttribute("picture", pictureService.selectPicture(id));
		return prefix + "/detail";
	}

	/**
	 * 新增
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap) {
		return prefix + "/add";
	}

	@RequiresPermissions("system:picture:upload")
	@RequestMapping("/upload")
	@ResponseBody
	public String uploadPic(MultipartFile file) throws IOException {
		if (!file.isEmpty()) {// 检查文件是否为空
			/**
			 * 使用FastDFS接口上传源图片到图片服务器
			 */
			String[] srcPath = FastDFSUtils.uploadFile(file.getBytes(), null, file.getOriginalFilename());
			/**
			 * 使用Thumbnails生成源图片的缩略图
			 */
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			Thumbnails.of(file.getInputStream())
				.size(300, 300)//缩略图大小
				.outputQuality(0.5)//缩略图质量
				.toOutputStream(baos);//写出OutputStream
			/**
			 * 使用FastDFS接口上传缩略图到图片服务器
			 */
			String[] thumbnailPath = FastDFSUtils.uploadFile(baos.toByteArray(), null, file.getOriginalFilename());

			/**
			 * 上传成功后拼接group和url获得完整路径， 把图片信息存入数据库， 返回成功信息
			 */
			if (srcPath.length == 2 && thumbnailPath.length == 2) {
				String srcpath = srcPath[0] + "/" + srcPath[1];
				String thumbnailpath = thumbnailPath[0] + "/" + thumbnailPath[1];
				Picture picture = new Picture(file.getOriginalFilename(), srcpath, thumbnailpath,"");
				picture.setCreateBy(getLoginName());
				pictureService.savePicture(picture);
				return "success";
			}
		}
		/**
		 * 上传失败 返回失败信息
		 */
		return "error";
	}

	@RequiresPermissions("system:picture:list")
	@GetMapping("/list")
	@ResponseBody
	public List<Picture> list(Picture picture) {
		List<Picture> pictureList = pictureService.selectPictureAll();
		return pictureList;
	}

	@RequiresPermissions("system:picture:random")
	@GetMapping("/random")
	@ResponseBody
	public Picture  alloc() throws IOException {
		KieSession kieSession = kieTemplate.getKieSession("rule1.drl");
		Picture picture = null;
		kieSession.insert(getUser());//插入当前登录的User信息
		kieSession.setGlobal("pictureService", pictureService);//实例化全局变量pictureService
		kieSession.fireAllRules();//激活所有规则
		/**
		 * 执行查询，获取查询结果并返回
		 * */
		QueryResults results = kieSession.getQueryResults("queryPicture");
		for (QueryResultsRow row : results) {
			picture = (Picture) row.get("$picture");
			System.out.println(picture.getPictureId());
		}
		return picture;

	}

}